﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmAmenitiesManager : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        DataTable items = new DataTable();
        string wrnEntMsg = "";

        bool addNew = false, prcErr = false,Committing = false,
            isViewing = false;
        UnityScript [] food;
        UnityElement curFood;
        //AutoChecker
        Timer tmr = new Timer();
        int curEdit = -1;

        public frmAmenitiesManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
            
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            //Start AutoCheck timer
            txtPrice.TextChanged += new EventHandler(CheckValue);

            txtSearch.KeyPress += new KeyPressEventHandler(txtSearch_KeyPress);
            btnAdd.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
            {
                txtName.Focus();
            });
            btnAdd.Click += new EventHandler(btnAdd_Click);
            mnuRemoveEntry.Click += new EventHandler(mnuRemoveEntry_Click);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            btnSave.Visible = false;
            btnAdd.Visible = false;
            btnCancel.Visible = false;
            btnCancel.Click += new EventHandler(btnCancel_Click);
            grdItems.DoubleClick += new EventHandler(grdItems_DoubleClick);
            pnlForm.Enabled = false;
            btnSave.Click +=new EventHandler(btnSave_Click);
            LoadAmenities();
        }

        void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13) t.MethodCall(LoadData);
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            addNew = false;
            foreach (Control ctl in grpDetails.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
            }
            txtType.SelectedIndex = 0;
            btnAdd.Visible = false;
            btnSave.Visible = false;
            btnCancel.Visible = false;
            txtName.Focus();
        }

        void grdItems_DoubleClick(object sender, EventArgs e)
        {
            curEdit = grdItems.SelectedRows[0].Index;
            food[0].Data_Get(curEdit, out curFood);

            txtType.Text = curFood.Data_GetField(0).ToString();
            txtName.Text = curFood.Data_GetField(1).ToString();
            txtPrice.Text = curFood.Data_GetField(2).ToString();

            btnAdd.Visible = false;
            btnSave.Visible = true;
            btnCancel.Visible = true;
            
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            Committing = true;
            addNew = false;
            States(false);
            CommitFood();
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            Committing = true;
            addNew = true;
            States(false);
            CommitFood();
        }
        
        void mnuRemoveEntry_Click(object sender, EventArgs e)
        {
           /* if (grdItems.SelectedRows.Count == 0) return;
            DialogResult dlg = MessageBox.Show("The entry will be permanently deleted from the list.\r\n" +
                "Do you wish to continue?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            int sel = grdItems.SelectedRows[0].Index;
            items.Rows[sel].Delete();
            t.MethodCall(CheckEntry);*/
        }
        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }
        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":
                        Committing = false;
                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "LOADAMENITIES":
                        UnityScript amenities;
                        proc.Data_Fetch(out amenities);
                        txtType.Items.AddRange(amenities.ToList(0));
                        pnlForm.Enabled = true;
                        if (txtType.Items.Count > 0) txtType.SelectedIndex = 0;

                        LoadFood();
                        break;
                    case "LOADDATA":
                    case "COMMIT":
                    case "LOADFOOD":
                        
                        proc.DBPUX_Data_Fetch(out food);
                        grdItems.DataSource = food[0].ToDataTable();
                        //Initialize Table Here
                        //Initialize Table Here
                        grdItems.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        grdItems.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

                        txtName.Text = "";
                        txtPrice.Text = "";
                        txtSearch.Text = "";
                        txtType.SelectedIndex = 0;
                        States(true);
                        addNew = false;
                        txtName.Focus();
                        btnAdd.Visible = false;
                        btnSave.Visible = false;
                        btnCancel.Visible = false;
                        txtName.Focus();

                        FormatTable();
                        break;
                    
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        lblWarningEntry.Text = "Loaded @ " + proc.ProcEnd() + " sec.";
                        break;
                };
                if (Committing || isViewing) return;
                tmr.Enabled = true;
                States(true);
            });
        }
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch(sender.ToString())
                {
                    case "CheckEntry":
                        lblWarningEntry.Text = wrnEntMsg;

                        if (prcErr)
                            txtPrice.ForeColor = Color.Red;
                        else
                            txtPrice.ForeColor = Color.Black;

                        if (!prcErr)
                            btnAdd.Visible = true;
                        else
                            btnAdd.Visible = false;
                        
                        break;
        
                }
                if (Committing) return;
                tmr.Enabled = true;
            });
        }

        //Operations
        void LoadData()
        {
            UnityScript u = new UnityScript("LOADDATA", 3);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fCategory AS 'Category', fName AS 'Name', fPrice AS 'Price', fStamp FROM tblamenitieslookup WHERE " +
                    "fCategory LIKE '%{0}%'  OR fName LIKE '%{0}%'", txtSearch.Text));
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void CheckEntry()
        {
            float fprice = 0f;
            string price = txtPrice.Text;
            //Check Price
            if (!float.TryParse(price, out fprice))
            {
                prcErr = true;
                wrnEntMsg = "";
                wrnEntMsg += "Invalid AMOUNT value detected!\r\n";
            }
            else
            {
                prcErr = false;
                if(!prcErr) wrnEntMsg = "";
            }
        }
        void CommitFood()
        {
            UnityScript u = new UnityScript("COMMIT", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            //Construct Expenses Items
            if (addNew)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblamenitieslookup(fCategory,fName, fPrice)",
                    new string[]{
                        txtType.Text,
                        txtName.Text,
                        txtPrice.Text
                    });
            }
            else
            {
                u.Script_Add(Script.DBPUX_UPDATE, string.Format("tblamenitieslookup SET " +
                    "fCategory = '{0}', fName='{1}', fPrice='{2}'", txtType.Text, txtName.Text, txtPrice.Text),
                    string.Format("(fID='{0}') AND (fStamp='{1}')", curFood.Data_ID.ToString(), curFood.Data_Stamp));
            }
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCategory AS 'Category', fName AS 'Name', fPrice AS 'Price', fStamp FROM tblamenitieslookup");
            //Transaction Log
            //u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
            //    new string[]{
                    //StoreClientModule.Common.Username,
            //        "Added " + txtPONum.Text + " worth " + gtotal.ToString("#,#0.00"),
            //        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
           //     });
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grdItems.Enabled = s;
        }
        //This will load amenities from lookup table
        void LoadAmenities()
        {
            UnityScript u = new UnityScript("LOADAMENITIES", 2);
            u.Script_Add(Script.DBPU_FETCH, "SELECT fData FROM tbllookup WHERE fKey='AMENITIES'");
            proc.Run(u);
        }
        void LoadFood()
        {
            UnityScript u = new UnityScript("LOADFOOD", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCategory AS 'Category', fName AS 'Name', fPrice AS 'Price', fStamp FROM tblamenitieslookup");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }

        void FormatTable()
        {
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                string value = grdItems.Rows[i].Cells[2].Value.ToString();
                grdItems.Rows[i].Cells[2].Value = float.Parse(value).ToString("#,#0.00");
            }
        }
        //Printing Module
        
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}